package org.wu.spring.orm.integration.compare.infrastructure.persistence.mybatis_flex;


import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.CollectionUtil;
import org.wu.framework.core.utils.LazyListUtils;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.wu.spring.orm.integration.compare.domain.model.sys.user.ORMComparisonRepository;
import org.wu.spring.orm.integration.compare.domain.model.sys.user.SysUser;
import org.wu.spring.orm.integration.compare.infrastructure.converter.SysUserConverter;
import org.wu.spring.orm.integration.compare.infrastructure.entity.SysUserDO;
import org.wu.spring.orm.integration.compare.infrastructure.mapper.flex.FlexSysUserMapper;
import org.wu.spring.orm.integration.compare.infrastructure.mapper.flex.SysUserTableDef;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.SysUserRepositoryAbstractRecord;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.enums.Orm;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.enums.Type;

import java.time.LocalDateTime;
import java.util.List;

/**
 * describe sys_user
 *
 * @author Jia wei Wu
 * @date 2024/02/28 11:27 上午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence
 **/
@Component("mybatis-flux")
public class MybatisFlexComparisonRepository extends SysUserRepositoryAbstractRecord
        implements ORMComparisonRepository {

    @Resource
    FlexSysUserMapper flexSysUserMapper;

    /**
     * describe 新增
     *
     * @param sysUser 新增
     * @return {@link Result<SysUser>} 新增后领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> story(SysUser sysUser) throws Exception {
        boolean success = true;
        super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        try {
            SysUserDO sysUserDO = SysUserConverter.INSTANCE.fromSysUser(sysUser);
            // 遇到唯一性索引 用户名、scope

            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select(SysUserTableDef.USER.DEFAULT_COLUMNS)
                    .from(SysUserTableDef.USER);
            if (!ObjectUtils.isEmpty(sysUserDO.getUsername())) {
                queryWrapper.and(SysUserTableDef.USER.USERNAME.eq(sysUserDO.getUsername()));
            }
            if (!ObjectUtils.isEmpty(sysUserDO.getScope())) {
                queryWrapper.and(SysUserTableDef.USER.SCOPE.eq(sysUserDO.getScope()));
            }

            boolean exists = CollectionUtil.isNotEmpty(flexSysUserMapper.selectObjectListByQuery(queryWrapper));
            if (exists) {
                flexSysUserMapper.updateByQuery(sysUserDO, queryWrapper);
            } else {
                flexSysUserMapper.insert(sysUserDO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.MYBATIS_FLEX, Type.story, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增
     *
     * @param sysUserList 批量新增
     * @return {@link Result<List<SysUser>>} 新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> batchStory(List<SysUser> sysUserList) throws Exception {
        boolean success = true;
                super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        try {
            List<SysUserDO> sysUserDOList = sysUserList.stream().map(SysUserConverter.INSTANCE::fromSysUser).toList();
            LazyListUtils.splitListThen(sysUserDOList,10000,flexSysUserMapper::batchStory);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.MYBATIS_FLEX, Type.batchStory, startTime, endTime, sysUserList.size(), success);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个
     *
     * @param sysUser 查询单个
     * @return {@link Result<SysUser>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> findOne(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findOne(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        try {
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select(SysUserTableDef.USER.DEFAULT_COLUMNS)
                    .from(SysUserTableDef.USER)
                    .where(
                            SysUserTableDef.USER.SCOPE.eq(sysUser.getScope())
                                    .and(SysUserTableDef.USER.USERNAME.eq(sysUser.getUsername()))
                    );
            // ... 逐一添加
            SysUserDO sysUserDO = flexSysUserMapper.selectOneByQuery(queryWrapper);
            SysUser sysUserOne = SysUserConverter.INSTANCE.toSysUser(sysUserDO);
            return ResultFactory.successOf(sysUserOne);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            LocalDateTime endTime = LocalDateTime.now();
            storyRecord(Orm.MYBATIS_FLEX, Type.findOne, startTime, endTime, success);
        }
        return ResultFactory.successOf();
    }

    /**
     * describe 查询多个
     *
     * @param sysUser 查询多个
     * @return {@link Result<List<SysUser>>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> findList(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findList(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        try {
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select(SysUserTableDef.USER.DEFAULT_COLUMNS)
                    .from(SysUserTableDef.USER)
                    .where(
                            SysUserTableDef.USER.SCOPE.eq(sysUser.getScope())
                                    .and(SysUserTableDef.USER.USERNAME.eq(sysUser.getUsername())));

            // ... 逐一添加

            List<SysUserDO> sysUserDOList = flexSysUserMapper.selectListByQuery(queryWrapper);

            List<SysUser> sysUserList = sysUserDOList.stream().map(SysUserConverter.INSTANCE::toSysUser).toList();
            return ResultFactory.successOf(sysUserList);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            LocalDateTime endTime = LocalDateTime.now();
            storyRecord(Orm.MYBATIS_FLEX, Type.findList, startTime, endTime, success);

        }
        return ResultFactory.successOf();

    }

    /**
     * describe 分页查询多个
     *
     * @param size    当前页数
     * @param current 当前页
     * @param sysUser 分页查询多个
     * @return {@link Result<LazyPage<SysUser>>} 分页领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<LazyPage<SysUser>> findPage(int size, int current, SysUser sysUser) throws Exception {
        boolean success = true;
        super.findList(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        try {
            Page<SysUserDO> page = new Page<>(current, size);

            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select(SysUserTableDef.USER.ALL_COLUMNS)
                    .from(SysUserTableDef.USER)
                    .where(
                            SysUserTableDef.USER.ID.eq(sysUser.getId())
                                    .and(SysUserTableDef.USER.USERNAME.eq(sysUser.getUsername())
                                            .and(SysUserTableDef.USER.IS_DELETED.eq(sysUser.getIsDeleted()))
                                    )
                    );

            // ... 逐一添加
            Page<SysUserDO> sysUserDOPage = flexSysUserMapper.paginate(current, size, queryWrapper);

            List<SysUserDO> records = sysUserDOPage.getRecords();
            long total = sysUserDOPage.getTotalRow();

            LazyPage<SysUser> lazyPage = new LazyPage<>(current, size);
            lazyPage.setTotal(total);
            lazyPage.setRecords(records.stream().map(SysUserConverter.INSTANCE::toSysUser).toList());
            return ResultFactory.successOf(lazyPage);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        } finally {
            LocalDateTime endTime = LocalDateTime.now();
            storyRecord(Orm.MYBATIS_FLEX, Type.findPage, startTime, endTime, size, success);
        }
        return ResultFactory.successOf();
    }

    /**
     * describe 删除
     *
     * @param sysUser 删除
     * @return {@link Result<SysUser>}
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> remove(SysUser sysUser) throws Exception {
        boolean success = true;
        super.remove(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        try {
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select(SysUserTableDef.USER.DEFAULT_COLUMNS)
                    .from(SysUserTableDef.USER)
                    .where(
                            SysUserTableDef.USER.SCOPE.eq(sysUser.getScope())
                                    .and(SysUserTableDef.USER.USERNAME.eq(sysUser.getUsername())));
            // ... 逐一添加

            flexSysUserMapper.deleteByQuery(queryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.MYBATIS_FLEX, Type.remove, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在
     *
     * @param sysUser 领域对象
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<Boolean> exists(SysUser sysUser) throws Exception {
        boolean success = true;
        super.exists(sysUser);
        boolean exists = false;
        LocalDateTime startTime = LocalDateTime.now();
        try {
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .select(SysUserTableDef.USER.DEFAULT_COLUMNS)
                    .from(SysUserTableDef.USER)
                    .where(
                            SysUserTableDef.USER.SCOPE.eq(sysUser.getScope())
                                    .and(SysUserTableDef.USER.USERNAME.eq(sysUser.getUsername())));

            // ... 逐一添加
            exists = CollectionUtil.isNotEmpty(flexSysUserMapper.selectObjectListByQuery(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.MYBATIS_FLEX, Type.exists, startTime, endTime, success);
        return ResultFactory.successOf(exists);
    }

}